package com.test.service.impl;

import com.test.exception.ServiceException;
import com.test.mapper.UserMapper;
import com.test.mapper.WebMapper;
import com.test.pojo.User;
import com.test.utils.TokenUtils;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 宋建华
 * @return
 * @date 2023-12-29
 */
@Service
public class WebService {
    @Autowired
    WebMapper webMapper;
    @Autowired
    UserMapper userMapper;

    public User login(User user) {
        User dbUser = webMapper.SelectByUserName(user.getUsername());
        if (dbUser == null) {
            throw new ServiceException("数据不存在");
        }
        // 注意这里用.equals进行校验的时候 要用前端的数据来进行校验
        // 如果是是后端在为空的话 会报空指针错误
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException("用户名或者密码错误");
        }

        // 生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }


    public User register(User user) {
        User dbUser = webMapper.SelectByUserName(user.getUsername());
        if (dbUser != null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名已存在");
        }
        user.setName(user.getUsername());
        webMapper.insert(user);
        return user;
    }

    public void resetPassword(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户不存在");
        }
        if (!user.getPhone().equals(dbUser.getPhone())){
            throw new ServiceException("数据错误");
        }
        dbUser.setPassword("123");   // 重置密码
        userMapper.updateUser(dbUser);
    }
}
